<?php
namespace app\controller\user;

use think\facade\Db;
use app\BaseController;
use think\facade\Cache;
use think\facade\Env;
use app\common;
use app\controller\user\Index as userIndex;

class Login extends BaseController{

    /**
     * 项目标识
     */
    private String $mark = "fl";

    /**
     * 微信通过code获取用户信息
     */
    public function getOpenidByCode($code){
        // $code = input('post.code');
        if (!$code) {
           return -1;
        }
        $appid = Env::get('wechat_data.appid');
        $secret = Env::get('wechat_data.secret');
        $url_left = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code=';
        $url_right = '&grant_type=authorization_code';
        $url = $url_left.$code.$url_right;
        $output = file_get_contents($url);
        // print_r(is_string($output));
        if ($output) {
            return self::getUserByOpenid(json_decode($output)->openid);
        }else{
            return BaseController::returnSuccessMsg('10003',"后台获取code失败");
        }
    }

    /**
     * 根据openid查询用户
     */
    public function getUserByOpenid($openid){
        $user = Db::name('user')->where('openid',$openid)->find();
        // 首先查询用户是否存在
        if (!$user) {
            // print_r("不存在用户");
            return self::registUser($openid);
        }
        return BaseController::returnSuccessMsg('10001',$user);
    }



    /**
     * 用户注册
     */
    public function registUser($openid){
        $params = input('post.');
        // 用户信息注册
        $userInfoData = ['nickname' => $params['nickname'],'city' => $params['city'],'sex' => $params['sex'],'avatar' => $params['avatar']];
        // 新增并返回用户信息id
        $uid = Db::name('user_info')->insertGetId($userInfoData);
        if (!$uid) {
            return BaseController::returnSuccessMsg('10003','用户信息新增失败');
        }
        // 信息注册成功，注册用户openid
        $userData = ['openid' => $openid,'permission' => 1,'info_id' => $uid];
        $userid = Db::name('user')->insertGetId($userData);
        if (!$userid) {
            $this->fallbackUserInsert(null,$uid);
            return BaseController::returnSuccessMsg('10003','无法获取用户id');
        }
        // 用户基本信息注册成功，注册个人财产
        $result = Db::name('user')->where('id',$userid)->find();
        // 个人财产注册
        $means = ['user_id'=>$result['id'],'balance'=>0,'status'=>1];
        $success = Db::name('means')->insert($means);
        if ($success != 1) {
            $this->fallbackUserInsert($userid,$uid);
            return BaseController::returnSuccessMsg('10003','注册失败');
        }
        return BaseController::returnSuccessMsg('10001',$result);
    }

    /**
     * 用户注册失败回滚
     */
    public function fallbackUserInsert($user,$ui){
        if ($user) {
            Db::name('user')->delete($user);
        }
        if ($ui) {
            Db::name('user_info')->delete($ui);
        }
        
    }

    /**
     * 每次进入小程序检验是否已经注册
     */
    public function varityhasuser(){
        $code = input("post.code");
        return self::getOpenidByCode($code);
    }

    /**
     * 登录
     * 返回token和用户信息
     */
    public function login(){
        $openid = input('post.openid');
        $ui = userIndex::getUiByOpenid($openid);
        // print_r(json($ui));
        $token = userIndex::updateUiInRedis(['openid'=>$openid,'user'=>$ui]);
        $data = ['data'=>$ui,'token'=>$token];
        return  BaseController::returnSuccessMsg('10001',$data);;
    }

    /**
     * 
     */


}

?>